package com.fjnu.interceptor;

import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MyListeners implements SessionListener{
	
	private static Logger logger =LogManager.getLogger(LoginInterceptor.class);
	@Override
	public void onStart(Session session) {
			
		logger.info("会话创建："+session.getId());
	}

	@Override
	public void onStop(Session session) {
		logger.info("会话撤销"+session.getId());
		
	}

	@Override
	public void onExpiration(Session session) {
		logger.info("会话过期"+session.getId());
		Map<String , Object> data = new HashMap<String, Object>();
		data.put("status", "fail");
		data.put("cause", "登录超时，请重新登录");
		HttpServletResponse response=
				((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		logger.debug(data);
		try {
			ObjectMapper mapper = new ObjectMapper();
			String jsonString = mapper.writeValueAsString(data);
			response.setCharacterEncoding("utf-8");
			Writer writer = new OutputStreamWriter(response.getOutputStream());
			writer.write(jsonString);
			writer.flush();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
	}

}
